package util;

import java.io.InputStream;
import java.sql.*;
import java.util.*;

public class JDBCUtil {

    private static final String driver;
    private static final String url;
    private static final String username;
    private static final String password;

    static {
        try {
            Properties props = new Properties();
            InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
            props.load(is);

            driver = props.getProperty("driver");
            url = props.getProperty("url");
            username = props.getProperty("username");
            password = props.getProperty("password");

            Class.forName(driver);
        } catch (Exception e) {
            throw new RuntimeException("加载数据库配置失败", e);
        }
    }

    /**
     * 获取数据库连接
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
    }

    /**
     * 释放资源
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            System.err.println("关闭资源时发生异常：" + e.getMessage());
        }
    }

    // 插入数据
    public static int insert(String sql, Object... params) {
        return executeUpdate(sql, params);
    }

    // 更新数据
    public static int update(String sql, Object... params) {
        return executeUpdate(sql, params);
    }

    // 删除数据
    public static int delete(String sql, Object... params) {
        return executeUpdate(sql, params);
    }

    // 执行更新（insert/update/delete）
    private static int executeUpdate(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            setParameters(ps, params);
            return ps.executeUpdate();

        } catch (SQLException e) {
            throw new RuntimeException("执行SQL更新失败: " + sql, e);
        } finally {
            close(conn, ps, null);
        }
    }

    // 查询数据
    public static List<Map<String, Object>> queryForList(String sql, Object... params) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Map<String, Object>> result = new ArrayList<>();

        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            setParameters(ps, params);
            rs = ps.executeQuery();

            while (rs.next()) {
                Map<String, Object> row = new HashMap<>();
                ResultSetMetaData metaData = rs.getMetaData();
                int columnCount = metaData.getColumnCount();

                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i);
                    row.put(columnName.toLowerCase(), value);
                }

                result.add(row);
            }

        } catch (SQLException e) {
            throw new RuntimeException("执行SQL查询失败: " + sql, e);
        } finally {
            close(conn, ps, rs);
        }

        return result;
    }

    // 设置参数
    private static void setParameters(PreparedStatement ps, Object... params) throws SQLException {
        for (int i = 0; i < params.length; i++) {
            ps.setObject(i + 1, params[i]);
        }
    }
}
